package org.openotdr.server;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.openotdr.server.file.Sr4731Converter;

import com.miyake.xml.MyXmlParser;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.google.appengine.repackaged.com.google.common.util.Base64DecoderException;

public class FileServlet extends HttpServlet implements Servlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6725011883157050131L;

	//private static Map<String, byte[]> map = new HashMap<String, byte[]>();
	
	public static final FileCache cacheFile = new FileCache("http://openotdr.appspot.com/fileServlet");
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String download = req.getParameter("download");
		
		if (req.getParameter("filelist") != null) {
			cacheFile.createListPage(req, resp);
			return;
		}
		
		if (download == null) {
			MyXmlParser parser = new MyXmlParser();
			parser.setName("SR4731 Parser");
			parser.setDescription("OTDR SR-4731 file parser");
			parser.setHelpUrl("http://openotdr.appspot.com");
			parser.setProvider("OtdrOtdrProject");
			parser.setVersion("1.00");
			parser.setLicense("Free");
			resp.setContentType("text/xml");   
	//		resp.getOutputStream().print(map.get(fileName));
			resp.getWriter().print(parser.encode());
			resp.getWriter().flush();
			resp.getWriter().close();
		}
		else if (download != null){
			cacheFile.downloadFile(req, resp);
		}

	}



	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		if (req.getParameter("test") != null) {
			test(req, resp);
			return;
		}
		
		if (req.getParameter("file")!= null) {
			cacheFile.cacheFile(req, resp);  
		}
		else {
			handleXML(req, resp);  
		}
 	}


	protected void test(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.getWriter().println("Post:Hello");
		if (req.getUserPrincipal() != null) {
			UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();
			resp.getWriter().println(user.getNickname());
			
			try {
				PersistenceManagerFactory factory = 
					JDOHelper.getPersistenceManagerFactory("transactions-optional");
			}
			catch (Exception e) {
				e.printStackTrace(resp.getWriter());
			}
		}

		resp.getWriter().flush();
		resp.getWriter().close();
	}

	protected void handleXML(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		BufferedInputStream bis = new BufferedInputStream(req.getInputStream());
		try {
			int len = bis.available();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
		    
		    byte[] buffer = new byte[8192];
		    while ((len = bis.read(buffer, 0, buffer.length)) != -1) {             
		    	baos.write(buffer, 0, len);
		    } 
		    baos.flush();
		    String s = new String(baos.toByteArray());
		    baos.close();
		    
		    byte[] b = null;
			try {
				b = Base64.decode(s);
			} catch (Base64DecoderException e) {
				e.printStackTrace(resp.getWriter());
			}
		    String xml = new Sr4731Converter(b, "Parsed").getXML();
		    resp.getWriter().print(xml);
		    resp.getWriter().flush();
		    resp.getWriter().close();
		    
		} catch (IOException e) {
			e.printStackTrace(resp.getWriter());
		}
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPut(req, resp);
	}

}
